import store from "../../store/store";
import $ from 'jquery'
import {config, url} from '../../util/config'
import {success} from "../../util/responseStatus";
import login from "../login";
import setUserLog from "../log/setUserLog";
function getNewLogin(id) {
    return downloadFile(id)
}
export default function downloadFile(id) {

    let token = localStorage.getItem("token")

    const download = function(local_id){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url.api_url+`FileList/DownloadFile?id=${local_id}`);    //也可以使用POST方式，根据接口
        xhr.setRequestHeader("Authorization",token);
        // xhr.setRequestHeader("Accept",'application/json');
        xhr.responseType = "blob";   //返回类型blob
        xhr.send();
        xhr.onload = function () {
            var blob = xhr.response;
            if(xhr.response.type == "application/json"){
                var reader = new FileReader();
                reader.readAsText(xhr.response);
                if(JSON.parse(reader.result).result=="Token過期請重新登錄"){
                    login(localStorage.getItem("account"), localStorage.getItem("password"));
                    getNewLogin(id)
                }
            }else {
                var fileName = xhr.getResponseHeader("FileName");
                // for IE
                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                }
                // for Non-IE (chrome, firefox etc.)
                else {
                    const a= document.createElement("a")
                    a.href = URL.createObjectURL(blob)
                    let strs = decodeURI(fileName).split("+");
                    let fileNameAfterMerge = "";
                    for(let i=0;i<strs.length;i++){
                        let separator = " ";
                        if(i==strs.length-1){
                            separator = "";
                        }
                        fileNameAfterMerge=fileNameAfterMerge + strs[i] + separator;
                    }
                    a.download = fileNameAfterMerge
                    a.click()
                    URL.revokeObjectURL(a.href)
                    a.remove();
                    setUserLog({title:fileNameAfterMerge,type:"file",id:id})
                }
            }

        };
    }

    download(id);

}
